package com.icangya.interceptor;

import com.icangya.domain.Admin;
import com.icangya.domain.User;
import com.icangya.service.IDomainService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.icangya.Value.FootBall.MOBILE_USER_SESSION;
import static com.icangya.Value.StaticValue.ADMIN_USER_SESSION;

/**
 * 登录拦截器
 */
public class MobileLoginInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = Logger.getLogger(MobileLoginInterceptor.class);


    @Autowired
    private IDomainService iDomainService;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
//        /** 拦截到用户的请求了 */
        String requestUrl = request.getRequestURL().toString();
        logger.debug("requestUrl:" + requestUrl);
        /** 判断session是否存在用户,如果存在说明用户已经登录了,应该放行 */
        User user = (User) request.getSession().getAttribute(MOBILE_USER_SESSION);

       if (user != null) {
            logger.debug("requestUrl:" + requestUrl + "->被放行！");
            //** 当前请求：每个请求是否都是一个线程   *//*
            //LoginInterceptor.addCurrentUser(user);
           response.sendRedirect("http://"+iDomainService.getDoamin().get(0).getDomainUrl() + "/footballgame/index.html");//Football.html //跳转到我们的游戏界面  足球小将
            return false;
        } else {
            // 重定向
//            response.sendRedirect(request.getContextPath() + "/index.html");
//            logger.debug("requestUrl:" + requestUrl + "->被拦截！");
//            return false;
           return true;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
       // LoginInterceptor.removeCurrentUser();
    }


   // private static ThreadLocal<AdminDO> users = new ThreadLocal<>();

//    public static void addCurrentUser(AdminDO user) {
//        if (users.get() == null) {
//            users.set(user);
//        }
//    }
//
//    public static AdminDO getCurrentUser() {
//        return users.get();
//    }
//
//    public static void removeCurrentUser() {
//        users.remove();
//    }

}
